package com.lagou.edu.service.impl;

import com.lagou.edu.dao.TokenDao;
import com.lagou.edu.dao.UserDao;
import com.lagou.edu.pojo.Token;
import com.lagou.edu.pojo.User;
import com.lagou.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private TokenDao tokenDao;

    @Override
    public int register(String email, String password, String code) {
        try {
            User user = new User();
            user.setEmail(email);
            user.setPassword(password);
            userDao.save(user);
            return 0;
        } catch (Exception ex) {
            return 1;
        }
    }

    @Override
    public boolean isRegistered(String email) {
        return userDao.existsUserByEmail(email);
    }

    @Override
    public String login(String email, String password) {
        User user = userDao.findByEmail(email);
        if (user != null && user.getPassword().equals(password)) {
            Token token = new Token();
            token.setEmail(email);
            String uuid = UUID.randomUUID().toString();
            token.setToken(uuid);
            tokenDao.save(token);
            return uuid;
        }
        return "false";
    }

    @Override
    public String info(String token) {
        Token obj = tokenDao.findByToken(token);
        return obj.getToken();
    }

}